# main.py
from fastapi import FastAPI
from contextlib import asynccontextmanager
# ✅ 修正：确保导入了 get_pool_instance
from database import get_pool_instance  # 这行必须包含 get_pool_instance
from config import settings
from apis.charging_station_api import router as charging_station_router

# --- 当需要添加新表时，导入新路由 ---
# from apis.user_api import router as user_router
# from apis.order_api import router as order_router
@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    print("应用正在启动...")
    try:
        # ✅ 使用新函数：直接 await 获取池实例
        pool = await get_pool_instance()
        print("✅ 数据库连接池初始化成功！")
        # 可以在这里进行其他初始化...
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        raise

    yield # 应用运行

    # 关闭连接池
    global _pool
    if _pool is not None:
        print("正在关闭数据库连接池...")
        await _pool.close()
        _pool = None
        print("数据库连接池已关闭。")


# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_TITLE,
    description=settings.APP_DESCRIPTION,
    lifespan=lifespan
)

# --- 挂载 API 路由 ---
app.include_router(charging_station_router)
# --- 当需要添加新表时，挂载新路由 ---
# app.include_router(user_router, prefix="/users")
# app.include_router(order_router, prefix="/orders")

@app.get("/")
def read_root():
    return {"message": "欢迎使用宁电热力图 API", "docs": "/docs"}

import sys
print(f"数据库模块路径: {sys.modules['database'].__file__}")